// useReducer
import { useReducer } from "react";
// 1.定义reducer函数 根据不同的action返回不同的状态
function numReducer(number, action) {
  // 返回一个新的state
  switch (action.type) {
    case "INC":
      return number + 1;
    case "DEC":
      return number - 1;
    case "UPDATE":
      return action.payload; // 根据传递的payload参数返回新的状态
    default:
      return number;
  }
}

function App() {
  // 2.在组件中调用useReducer(reducer函数,初始值) => [state,dispatch] state:状态 dispatch:修改状态的方法
  const [number, numDispatch] = useReducer(numReducer, 0);
  return (
    <>
      <div>{number}</div>
      {/* 3.调用dispatch传入action对象 dispatch({type:"INC"}) => 通知reducer产生一个新的状态，使用新状态更新视图 */}
      <button onClick={() => numDispatch({ type: "INC" })}>+</button>
      <button onClick={() => numDispatch({ type: "DEC" })}>-</button>
      {/* 4.调用action传参 dispatch({type:"UPDATE":payload:参数}) reducer函数可以根据传递的payload参数返回新的状态 */}
      <button onClick={() => numDispatch({ type: "UPDATE", payload: 100 })}>
        update to 100
      </button>
    </>
  );
}

export default App;
